import AMapLoader from '@amap/amap-jsapi-loader';
import React, { useEffect, useRef } from 'react';

declare global {
  interface Window {
    _AMapSecurityConfig: {
      securityJsCode: string;
    };
  }
}

// 定义聚合点上下文接口
interface ClusterContext {
  clusterData:any[]
  count: number;
  marker: any;
  markers: any[];
}

// 定义单个点标记上下文接口
interface MarkerContext {
  count: number;
  marker: any; // 如果知道具体类型可以替换为更精确的类型
  data: any[];
  indexs?: any; // 由于可能为 undefined，使用可选属性
}

//#region
// 坐标集
const points = [
  { weight: 5, lnglat: [115.3833, 38.8667], name: "保定西站", img: "/images/1.png" },
  { weight: 7, lnglat: [115.5833, 38.8667], name: "保定东站", img: "/images/2.jpg" },
  { weight: 6, lnglat: [115.4833, 38.7567], name: "保定动物园", img: "/images/3.jpg" },
  { weight: 9, lnglat: [115.4833, 38.9767], name: "保定植物园", img: "/images/4.png" },
  { weight: 3, lnglat: [115.4333, 38.8167], name: "直隶总督署", img: "/images/5.jpg" },
  { weight: 8, lnglat: [115.5333, 38.9167], name: "古莲花池", img: "/images/6.jpg" },
  { weight: 4, lnglat: [115.4133, 38.9167], name: "保定军校纪念馆", img: "/images/6.jpg" },
  { weight: 5, lnglat: [115.5533, 38.8167], name: "大慈阁", img: "/images/7.png" },
  { weight: 6, lnglat: [115.4633, 38.8867], name: "竞秀公园", img: "/images/8.png" },
  { weight: 7, lnglat: [115.5033, 38.8467], name: "人民广场", img: "/images/9.jpg" },
  { weight: 2, lnglat: [115.3633, 38.9067], name: "万博广场", img: "/images/10.jpg" },
  { weight: 10, lnglat: [115.6033, 38.8267], name: "未来石万达广场", img: "/images/11.jpg" },
  { weight: 1, lnglat: [115.4833, 38.7167], name: "清苑古城", img: "/images/12.jpg" },
  { weight: 8, lnglat: [115.4833, 39.0167], name: "徐水大午温泉度假村", img: "/images/13.jpg" },
  { weight: 4, lnglat: [115.2833, 38.8667], name: "满城汉墓", img: "/images/14.jpg" },
  { weight: 9, lnglat: [115.6633, 38.8667], name: "白洋淀温泉城", img: "/images/15.jpg" },
  { weight: 3, lnglat: [115.4833, 38.6667], name: "冉庄地道战遗址", img: "/images/16.jpg" },
  { weight: 6, lnglat: [115.4833, 39.0867], name: "易水湖", img: "/images/17.png" },
  { weight: 5, lnglat: [115.2333, 38.8667], name: "狼牙山", img: "/images/18.png" },
  { weight: 7, lnglat: [115.7133, 38.8667], name: "野三坡", img: "/images/19.png" },
  { weight: 5, lnglat: [117.0901, 39.1255], name: "天津滨海国际机场", img: "/images/1.png" },
  { weight: 7, lnglat: [117.2901, 39.1255], name: "天津滨海文化中心", img: "/images/2.jpg" },
  { weight: 6, lnglat: [117.1901, 39.0155], name: "天津国家海洋博物馆", img: "/images/3.jpg" },
  { weight: 9, lnglat: [117.1901, 39.2355], name: "意式风情区", img: "/images/4.png" },
  { weight: 3, lnglat: [117.1401, 39.0755], name: "天津之眼", img: "/images/5.jpg" },
  { weight: 8, lnglat: [117.2401, 39.1755], name: "五大道文化旅游区", img: "/images/6.jpg" },
  { weight: 4, lnglat: [117.1201, 39.1755], name: "天津博物馆", img: "/images/6.jpg" },
  { weight: 5, lnglat: [117.2601, 39.0755], name: "南市食品街", img: "/images/7.png" },
  { weight: 6, lnglat: [117.1701, 39.1455], name: "解放桥", img: "/images/8.png" },
  { weight: 7, lnglat: [117.2101, 39.1055], name: "世纪钟", img: "/images/9.jpg" },
  { weight: 2, lnglat: [117.0701, 39.1655], name: "天津西站", img: "/images/10.jpg" },
  { weight: 10, lnglat: [117.3101, 39.0855], name: "天津站", img: "/images/11.jpg" },
  { weight: 1, lnglat: [117.1901, 38.9755], name: "天津滨海航母主题公园", img: "/images/12.jpg" },
  { weight: 8, lnglat: [117.1901, 39.2755], name: "天津水上公园", img: "/images/13.jpg" },
  { weight: 4, lnglat: [116.9901, 39.1255], name: "杨柳青古镇", img: "/images/14.jpg" },
  { weight: 9, lnglat: [117.3701, 39.1255], name: "天河城购物中心", img: "/images/15.jpg" },
  { weight: 3, lnglat: [117.1901, 38.9255], name: "官港森林公园", img: "/images/16.jpg" },
  { weight: 6, lnglat: [117.1901, 39.3455], name: "北宁公园", img: "/images/17.png" },
  { weight: 5, lnglat: [116.9401, 39.1255], name: "平津战役纪念馆", img: "/images/18.png" },
  { weight: 7, lnglat: [117.4301, 39.1255], name: "天津文化中心图书馆", img: "/images/19.png" },
  { weight: 8, lnglat: [116.297428, 39.90923], name: "北京首都国际机场", img: "/images/1.png" },
  { weight: 8, lnglat: [116.497428, 39.90923], name: "北京环球度假区", img: "/images/2.jpg" },
  { weight: 8, lnglat: [116.397428, 39.80923], name: "北京野生动物园", img: "/images/3.jpg" },
  { weight: 8, lnglat: [116.397428, 40.00923], name: "八达岭长城", img: "/images/4.png" },
  { weight: 8, lnglat: [116.357428, 39.85923], name: "北京大观园", img: "/images/5.jpg" },
  { weight: 8, lnglat: [116.437428, 39.95923], name: "鸟巢（国家体育场）", img: "/images/6.jpg" },
  { weight: 8, lnglat: [116.327428, 39.95923], name: "颐和园", img: "/images/6.jpg" },
  { weight: 8, lnglat: [116.467428, 39.85923], name: "北京南站", img: "/images/7.png" },
  { weight: 8, lnglat: [116.387428, 39.92923], name: "北京故宫博物院", img: "/images/8.png" },
  { weight: 8, lnglat: [116.407428, 39.88923], name: "天坛公园", img: "/images/9.jpg" },
  { weight: 8, lnglat: [116.277428, 39.94923], name: "北京北站", img: "/images/10.jpg" },
  { weight: 8, lnglat: [116.517428, 39.86923], name: "北京通州万达广场", img: "/images/11.jpg" },
  { weight: 8, lnglat: [116.397428, 39.76923], name: "北京大兴国际机场", img: "/images/12.jpg" },
  { weight: 8, lnglat: [116.397428, 40.04923], name: "慕田峪长城", img: "/images/13.jpg" },
  { weight: 8, lnglat: [116.237428, 39.90923], name: "北京西山国家森林公园", img: "/images/14.jpg" },
  { weight: 8, lnglat: [116.557428, 39.90923], name: "北京朝阳大悦城", img: "/images/15.jpg" },
  { weight: 8, lnglat: [116.397428, 39.70923], name: "北京世界公园", img: "/images/16.jpg" },
  { weight: 8, lnglat: [116.397428, 40.10923], name: "雁栖湖", img: "/images/17.png" },
  { weight: 8, lnglat: [116.177428, 39.90923], name: "潭柘寺", img: "/images/18.png" },
  { weight: 8, lnglat: [116.617428, 39.90923], name: "北京欢乐谷", img: "/images/19.png" }
];
//#endregion

function Review() {
  //地图区域
  const mapContainer = useRef<HTMLDivElement>(null);
  //地图内容.地图实例
  const mapInstance = useRef<any>(null);

  //实现多点坐标时,将地图缩放到合适的大小,刚好能显示全部点位,同时有一定的边缘
  // AMap.Bounds() 区域  getCenter() 获取当前Bounds的中心点经纬度坐标
  // AMap.LngLat() 点坐标（基础点位）
  // AMap.setBounds() 设置地图区域，这会自动移动地图画面到这个区域中


  // 1.坐标点位对角线的中心点的坐标值 (最大坐标值和最小坐标值)
  function getMaxBoundsPointer(pointerArray: any[]) {
    let lngArray = pointerArray.map(item => item[0])
    let latArray = pointerArray.map(item => item[1])

    return {
      min: [Math.min(...lngArray), Math.min(...latArray)],
      max: [Math.max(...lngArray), Math.max(...latArray)],
    }
  }
  let maxLocations = getMaxBoundsPointer(points.map(item => item.lnglat))
  console.log(111, maxLocations)

  // 2.计算合适的地图边界距离
  let lngGap = (maxLocations.max[0] - maxLocations.min[0]) / 5
  let latGap = (maxLocations.max[1] - maxLocations.min[1]) / 5

  useEffect(() => {
    // 强制清理旧实例
    if (mapInstance.current) {
      mapInstance.current.destroy();
      mapInstance.current = null;
    }

    window._AMapSecurityConfig = {
      securityJsCode: "9540654b67af7aca12bbdbcfe477f128",
    };

    AMapLoader.load({
      key: "41e2d19fa0369f101e950c945767a093",
      version: "2.0",
      plugins: [
        'AMap.MarkerCluster',
        "AMap.Scale",
        "AMap.ToolBar"
      ]
    })
      .then((AMap) => {
        if (!mapContainer.current) return;

        // 3.计算新的区域值
        let min = new AMap.LngLat(maxLocations.min[0] - lngGap, maxLocations.min[1] - latGap)
        let max = new AMap.LngLat(maxLocations.max[0] + lngGap, maxLocations.max[1] + latGap)

        // 初始化地图（调高初始缩放级别）
        mapInstance.current = new AMap.Map(mapContainer.current, {
          viewMode: "2D",
          zoom: 9,  // 降低初始缩放级别以便观察聚合
          center: [116.397428, 39.90923],
        });

        // 4.设置地图中心点
        //多个点时,计算中心点
        if (points.length > 1) {
          let bounds = new AMap.Bounds(min, max)
          mapInstance.current.setBounds(bounds)
        }
        // 一个点时，将其作为中心点
        else if (points.length === 1) {
          let centerLngLat = new AMap.LngLat(points[0].lnglat)
          mapInstance.current.setCenter(centerLngLat)  // 设置地图中心点坐标
        }

        // 添加控件
        mapInstance.current.addControl(new AMap.Scale());
        mapInstance.current.addControl(new AMap.ToolBar());

        // 创建基准标记（红色）
        new AMap.Marker({
          position: [116.397428, 39.90923],
          content: '<div style="background:red;width:20px;height:20px;border-radius:50%"></div>',
          map: mapInstance.current
        });

        // 创建测试标记（不直接添加到地图）
        const markers = points.map(pos =>
          new AMap.Marker({ 
            position: pos.lnglat,
            content: '<div style="background:red;width:20px;height:20px;border-radius:50%"></div>',
            map:mapInstance.current
           }) // 关键：不设置map属性
        );

        //初始化聚合层（使用正确类名）
        // const cluster = new AMap.MarkerCluster(
        //   mapInstance.current,
        //   points,
        //   {
        //     gridSize: 80,         // 适当增大网格尺寸
        //     minClusterSize: 2,    // 最小聚合数量
        //     maxZoom: 15,        // 最大聚合级别
        //     //为聚合点自定义     
        //     renderMarker: (context: MarkerContext) => {
        //       context.marker.setContent(`
        //           <div style="
                    
        //             border: 2px solid black;
        //             font-size: 12px;
        //             padding:2px;
        //           ">
        //             <div style="font-size: 10px; font-weight: bold; margin-bottom: 5px;">${context.data[0].name}</div>
        //             <img src="${context.data[0].img}" alt="${context.data[0].name}" style="width: 40px; height: 40px;">
        //           </div>
        //         `)

        //       context.marker.on('dblclick', () => {
        //         console.log(789)
        //       })
        //     },
        //     //聚合点自定义
        //     renderClusterMarker: (context: ClusterContext) => {
        //       context.marker.setContent(`
        //         <div style="
        //           width: 40px;
        //           height: 40px;     
        //           border-radius:50%;
        //           background-color:${context.count>=20?"yellow":context.count>=10?"blue":"green"};
        //           color:white; 
        //           text-align:center;
        //           line-height:40px;                 
        //         ">
        //           ${context.count}
        //         </div>
        //       `)
        //       // 双击聚合点可以将地图进一步放大显示
        //       context.marker.on('dblclick', () => {
        //         console.log('双击聚合点', context);
        //         const currentZoom = mapInstance.current.getZoom();
        //         mapInstance.current.setZoomAndCenter(
        //           Math.min(currentZoom + 2, 18),
        //           context.marker.getPosition()
        //         );
        //       })
        //     }
        //   })


        // //调试信息
        // console.log('总标记数:', points.length);
        // console.log('初始聚合数:', cluster.getClustersCount());
      })
      .catch(console.error);
  }, []);


  return (
    <div>
      <h2>精准点聚合演示</h2>
      <div
        ref={mapContainer}
        style={{
          width: "77vw",
          height: "80vh",
          border: "3px solid #4CAF50"
        }}
      />
    </div>
  );
}


export default Review;